package com.horay.springbootdemo.jwt.customer.controller;

import com.horay.springbootdemo.common.enums.ResultState;
import com.horay.springbootdemo.common.result.ResultBody;
import com.horay.springbootdemo.jwt.common.annotation.CustomerLoginToken;
import com.horay.springbootdemo.jwt.common.jwt.JwtUtils;
import com.horay.springbootdemo.jwt.common.model.Customer;
import com.horay.springbootdemo.jwt.customer.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * 顾客控制器
 *
 * @author heyingcheng
 * @date 2019/10/4 12:43
 */
@RestController
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping("/login")
    public ResultBody<String> login(@RequestBody Customer requestCustomer) {
        ResultBody<String> resultBody = new ResultBody<>();
        Optional<Customer> customerOptional = customerService.findById(requestCustomer.getId());
        if (!customerOptional.isPresent()) {
            resultBody.setCode(ResultState.Failure.code);
            resultBody.setMessage("登录失败, 用户不存在");
            return resultBody;
        } else {
            Customer dbCustomer = customerOptional.get();
            if (!dbCustomer.getPassword().equals(requestCustomer.getPassword())) {
                resultBody.setCode(ResultState.Failure.code);
                resultBody.setMessage("登录失败, 密码错误");
                return resultBody;
            } else {
                String token = JwtUtils.token(dbCustomer);
                resultBody.setCode(ResultState.Success.code);
                resultBody.setMessage(token);
                resultBody.setData(dbCustomer.getId());
                return resultBody;
            }
        }
    }

    @CustomerLoginToken
    @GetMapping("/message")
    public String getMessage() {
        return "您已通过验证";
    }

}
